import wepy from 'wepy';
import {base64Encode,encrypt} from './aes';
let sha1 = require('./sha1.js').sha1;

import tip from './tip'
const defaultIntData = {session_id:'00000000000000000000000000000000',key : '00000000000000000000000000000000'};

  // 获取当前格式化时间
  const getCurrentTime = () => {
    let keep = ''
    let date = new Date()
    let y = date.getFullYear()
    let m = date.getMonth() + 1
    m = m < 10 ? '0' + m : m
    let d = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
    let h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
    let f = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
    let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
    keep = y + '' + m + '' + d + '' + h + '' + f + '' + s
    return keep // 20160614134947
  }

  // 验证是否是手机号码
  const vailPhone = (number) => {
    return /^1[34578]\d{9}$/.test(number)
  }

  // 验证是否是邮箱
  const vailEmail = (strEmail) => {
    let reg=/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
    return strEmail != null && strEmail.search(reg) != -1;
  }

  // 验证是否包含汉字
  const vailChineseFont = (val) => {
      let reg = new RegExp("[\\u4E00-\\u9FFF]+","g");
      return reg.test(val);
  }

  // 验证qq号码
  const vailQQ = (qq) => {
    let reg = /^[1-9][0-9]{4,9}$/g;
    return reg.test(qq);
  }

  // 验证Emoji表情
  const vailEmoji = (val) => {
    const reg = /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/ig;
    return reg.test(val);
  }


  //  去除字符串所有空格
  const sTrim = (text) => {
    return text.replace(/\s/g, '')
  }

  // 获取系统信息
  const getSystemInfo = ()=>{
    return wepy.getSystemInfoSync();
  }
  // 获取时间戳
  const getTimestampOfSecends = () => {
    return parseInt((new Date()).getTime()/1000)
  }
  // 获取签名戳
  const getSignature = (action,session_id,reqRaw,timestamp,key) => {
    let post_data = `action=${action}&session_id=${session_id}&reqRaw=${reqRaw}&timestamp=${timestamp}`;
    let new_post_str = `${key}&${timestamp}=<${post_data}>&`;
    let str = sha1(new_post_str);
    return str.substr(20) + str.substr(0, 20);
  }
  // base64加密
  const getReqRaw = (data,USEAES) => {
    data = JSON.stringify(data);
    if(USEAES){
      return encrypt(data,getSess('iv'),getSess('key'));
    }
    return base64Encode(data);
  }
  // 微信登陆
  const getWxLoginCode = ()=>new Promise((resolve)=>{
    wepy.login().then(res=>{
      return resolve(res.code)
    })
  })
 // 检查登陆是否过期
  const checkSession = ()=>new Promise((resolve)=>{
    if(!wepy.getStorageSync('initData')){
      return resolve(true);
    }
    wepy.checkSession().then(res=>{
      console.log('session_key 未过期',res)
      return resolve(false)
    }).catch(res=>{
      console.log('session_key 已过期，重新执行初始化',res)
      return resolve(true)
    })
  })

 

  // 获取缓存的初始化数据
  const getSess = (key,action)=>{
    if(action==1006){
      return defaultIntData[key];
    }
    const sess = wepy.getStorageSync('initData')[key];
    return sess?sess:defaultIntData[key];
    
  }

  // 获取当前页面路径
  const getCurrentPage = ()=>{
    let pages = getCurrentPages()
    let currentPage = pages[pages.length-1]
    let prePage = pages.length>1?pages[pages.length-2]:'';
    let url = currentPage.route;
    let options = currentPage.options;
    return {url,options,prePage,currentPage}
  }


  const countDown = (tfutureTime, tnowTime) => {
    let sumMS = tfutureTime - tnowTime;
    let day = Math.floor(sumMS / 60 / 60 / 24);
    let hour = Math.floor(sumMS / 60 / 60 % 24);
    let minute = Math.floor(sumMS / 60 % 60);
    let second = Math.floor(sumMS % 60);

    if (day < 10) {
      day = "0" + day;
    }
    if (hour < 10) {
      hour = "0" + hour;
    }
    if (minute < 10) {
      minute = "0" + minute;
    }
    if (second < 10) {
      second = "0" + second;
    }

    return {
      day, hour, minute, second
    }
}


/* 定时器实现节流 */
let clickFlag = false;
const throttle = async(func,delay=500) => {
  let netWork = await onNetworkStatusChange();
    if(!netWork) return tip.loaded();
    
    if(!clickFlag){
        func();
        clickFlag=true;
        let timer = setTimeout(()=>{
            clickFlag = false;
            clearTimeout(timer);
        },delay);
    }
};

//监听网络状态变化
const onNetworkStatusChange = ()=>new Promise((resolve) => { 
  // return resolve(false);
  wx.getNetworkType({
    success(res) {
      const networkType = res.networkType === 'none';
      if (networkType) {
        tip.toast('当前无网络',false,'loading')
      }
      return resolve(!networkType)
    }
  });
  wx.onNetworkStatusChange(res => {
    if (!res.isConnected) {
      tip.toast('网络已断开',()=>{
          //可以跳转到错误页面
      },'loading')
    }
    return resolve(!res.isConnected)
  })

})

//版本更新
const updataApp = ()=> {
  if (wepy.canIUse('getUpdateManager')) {
    const updateManager = wx.getUpdateManager()
    updateManager.onCheckForUpdate(function (res) {
      console.log('版本更新1',res)
      if (res.hasUpdate) { // 请求完新版本信息的回调
        updateManager.onUpdateReady(function () {
          tip.confirm('新版本已经准备好，是否重启应用？',{},'更新提示').then(()=>updateManager.applyUpdate());
        })
        updateManager.onUpdateFailed(function () {
          tip.confirm('当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',{},'已经有新版本了哟~')
        })
      }
    })
  } else {
    tip.confirm('当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。')
  }
} 


  module.exports = {
    countDown,
    defaultIntData,
    getCurrentTime,
    sTrim,
    vailPhone,
    vailEmail,
    vailChineseFont,
    vailQQ,
    vailEmoji,
    getSystemInfo,
    getSignature,
    getReqRaw,
    getTimestampOfSecends,
    getWxLoginCode,
    checkSession,
    getSess,
    getCurrentPage,
    throttle,
    onNetworkStatusChange,
    updataApp,
  }
  